<?php

class LoginController extends Controller
{
	public $layout = "login/main.php";
	public function actionIndex()
	{
      $model=new LoginForm;
		// Kiem tra xem user da login hay chua?
		if(!Yii::app()->user->isGuest)
		{
			$this->redirect(Yii::app()->homeUrl);
		}
		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the Dashbroad if correct
			//$this->actionLostPassword();
			yii::log('************ yii log :'.$model->validate());
			if($model->validate()){
			  if  ($model->login()){
				$this->redirect(Yii::app()->homeUrl);
				}
			  yii::log('********** login log'.$model->login());
			}
			
				
		}
		
		$this->render('index',array('model'=>$model));
		
	}

	public function actionLostPassword()
	{   
		$model=new LostPasswordForm;
	  Yii::log("chay -> nhan duoc hang ".$model->useremail." ok");
		
	// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='lostpassword-form')
		{
			Yii::log("nhan duoc hang validation request ");
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
		
		 //collect username or email data 
		 if(isset($_POST['LostPasswordForm']))
		 {
		 	Yii::log("**** nhan duoc form ");
		 	//$this->redirect(Yii::app()->homeUrl); 
		  $model->attributes=$_POST['LostPasswordForm'];
		  //validate user input and call the lostPassword Method in LostPaswordForm
		  if($model->validate() ){
		  	if($model->lostPassword()){
			 Yii::log ("***validate email vs chay phuong thuc lostPassword xong ");
			  Yii::app()->user->setFlash('lostpassword','your password has been reseted. Please check your email.'); 
			  //$this->refresh();
		  		}
			 else {
			 	
			 Yii::app()->user->setFlash('lostpassword','error ! We can\'t send email to you');
			// $this->refresh();
			 } 
		  }
		 }
		
		
		
		$this->render('lostpassword',array('model'=>$model));
	}

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}